package com.cps.platform.service.config.spi;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.cps.platform.client.hbase.HbaseClient;
import com.cps.platform.core.hbase.HbasePut;

/**
 * <p>
 * 文件名称: RelyHbase.java
 * </p>
 * <p>
 * 文件描述: 配置依赖HBASE服务，需要将配置数据存储于HBASE服务中
 * <p>
 * 版权所有: 版权所有(C)2011
 * </p>
 * <p>
 * 公 司: 联通系统集成有限公司
 * </p>
 * <p>
 * 完成日期：2012-12-7
 * </p>
 * 
 * @author ChenZhang
 */
class RelyHbase {

	private static Logger log = Logger.getLogger(RelyHbase.class);
	
	private HbaseClient client;
	private String rowkey;
	private String appId;
	private String authToken;
	private String tenantId;
	private String configTableName;
	
	public RelyHbase(String configTableName, String rowkey, 
			String appId, String authToken, String tenantId) {
		
		this.configTableName = configTableName;
		this.rowkey = rowkey;
		this.appId = appId;
		this.authToken = authToken;
		this.tenantId = tenantId;
		
		client = new HbaseClient();
		
		log.info("OK");
	}
	
	/**
	 * 获取服务的配置数据
	 * @return
	 */
	public HbasePut getConfig() {
		try{
			return this.client.getData(appId, authToken, tenantId, configTableName, rowkey);
		}catch(Exception e){
			return null;
		}
		
	}

	/**
	 * 向服务添加配置数据
	 * @param key
	 * @param value
	 * @return
	 */
	public HbasePut addConfig(String key, String value) {
		HbasePut hbasePut = this.getConfig();

		Map<String, String> kv = null;
		if(hbasePut==null) {
			hbasePut = new HbasePut();
			hbasePut.setTableName(configTableName);
			hbasePut.setRowKey(rowkey);
			kv = new HashMap<String, String>();
		}else{
			kv = hbasePut.getKeyValues();
		}
		
		kv.put(key, value);
		hbasePut.setKeyValues(kv);
		return client.saveData(appId, authToken, tenantId, hbasePut);
	}

	/**
	 * 移出配置数据
	 * @param key
	 * @return
	 */
	public HbasePut removeConfig(String key) {
		HbasePut hbasePut = this.getConfig();
		if(hbasePut!=null){
			removeConfig();
			Map<String, String> kv = hbasePut.getKeyValues();
			kv.remove(key);
			hbasePut.setKeyValues(kv);
			return client.saveData(appId, authToken, tenantId, hbasePut);
		}else{
			return null;
		}
	}

	/**
	 * 移出服务的所有配置数据
	 * @return
	 */
	public boolean removeConfig() {
		return client.removeData(appId, authToken, tenantId, configTableName, rowkey);
	}
	
}
